import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Box,
  Typography,
  Alert,
  Grid,
  FormControlLabel,
  Switch,
} from '@mui/material';
import { Iconify } from 'src/components/iconify';
import { safeApiCall, getAuthHeader } from 'src/utils/api';

interface TemplateForm {
  templateName: string;
  templateCategory: string;
  templateDescription: string;
  ruleConfig: string;
  isPublic: boolean;
}

interface AutoAccountingTemplateEditDialogProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  template?: any; // 编辑时的模板数据
}

export function AutoAccountingTemplateEditDialog({
  open,
  onClose,
  onSuccess,
  template,
}: AutoAccountingTemplateEditDialogProps) {
  const [form, setForm] = useState<TemplateForm>({
    templateName: template?.templateName || '',
    templateCategory: template?.templateCategory || 'EXPENSE',
    templateDescription: template?.templateDescription || '',
    ruleConfig: template?.ruleConfig || '',
    isPublic: template?.isPublic || false,
  });
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [severity, setSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');

  const handleSubmit = async () => {
    // 表单验证
    if (!form.templateName.trim()) {
      setMessage('请输入模板名称');
      setSeverity('error');
      return;
    }
    if (!form.templateCategory.trim()) {
      setMessage('请选择模板分类');
      setSeverity('error');
      return;
    }
    if (!form.templateDescription.trim()) {
      setMessage('请输入模板描述');
      setSeverity('error');
      return;
    }

    try {
      setLoading(true);
      const url = template ? `/api/auto-accounting/templates/${template.id}` : '/api/auto-accounting/templates';
      const method = template ? 'PUT' : 'POST';
      const result = await safeApiCall(url, method, form, getAuthHeader());
      console.log('',result);
      if (result.success) {
        setMessage(template ? '模板更新成功' : '模板创建成功');
        setSeverity('success');
        setTimeout(() => {
          onSuccess();
          resetForm();
        }, 1000);
      } else {
        setMessage(result.error || (template ? '更新模板失败' : '创建模板失败'));
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error saving template:', error);
      setMessage(template ? '更新模板失败' : '创建模板失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setForm({
      templateName: '',
      templateCategory: 'EXPENSE',
      templateDescription: '',
      ruleConfig: '',
      isPublic: false,
    });
    setMessage('');
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Box display="flex" alignItems="center" gap={1}>
          <Iconify icon="eva:plus-circle-fill" color="primary.main" />
          {template ? '编辑模板' : '创建模板'}
        </Box>
      </DialogTitle>
      
      <DialogContent>
        {message && (
          <Alert severity={severity} sx={{ mb: 2 }} onClose={() => setMessage('')}>
            {message}
          </Alert>
        )}

        <Box sx={{ pt: 1 }}>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="模板名称"
                value={form.templateName}
                onChange={(e) => setForm({ ...form, templateName: e.target.value })}
                placeholder="例如：餐饮消费模板"
                helperText="为模板起一个容易识别的名称"
              />
            </Grid>
            
            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>模板分类</InputLabel>
                <Select
                  value={form.templateCategory}
                  onChange={(e) => setForm({ ...form, templateCategory: e.target.value })}
                  label="模板分类"
                >
                  <MenuItem value="EXPENSE">支出</MenuItem>
                  <MenuItem value="INCOME">收入</MenuItem>
                  <MenuItem value="TRANSPORT">交通</MenuItem>
                  <MenuItem value="FOOD">餐饮</MenuItem>
                  <MenuItem value="LIVING">生活</MenuItem>
                  <MenuItem value="ENTERTAINMENT">娱乐</MenuItem>
                  <MenuItem value="OTHER">其他</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="模板描述"
                value={form.templateDescription}
                onChange={(e) => setForm({ ...form, templateDescription: e.target.value })}
                multiline
                rows={3}
                placeholder="详细描述这个模板的用途和适用场景"
                helperText="帮助用户理解模板的用途"
              />
            </Grid>

            <Grid item xs={12}>
              <TextField
                fullWidth
                label="规则配置"
                value={form.ruleConfig}
                onChange={(e) => setForm({ ...form, ruleConfig: e.target.value })}
                multiline
                rows={6}
                placeholder="输入JSON格式的规则配置"
                helperText="JSON格式的规则配置，包含所有必要的规则参数"
              />
            </Grid>

            <Grid item xs={12}>
              <FormControlLabel
                control={
                  <Switch
                    checked={form.isPublic}
                    onChange={(e) => setForm({ ...form, isPublic: e.target.checked })}
                  />
                }
                label="公开模板"
              />
              <Typography variant="caption" color="text.secondary" display="block" sx={{ ml: 4 }}>
                公开的模板可以被其他用户使用
              </Typography>
            </Grid>
          </Grid>
        </Box>
      </DialogContent>
      
      <DialogActions>
        <Button onClick={handleClose}>取消</Button>
        <Button onClick={handleSubmit} variant="contained" disabled={loading}>
          {loading ? (template ? '更新中...' : '创建中...') : (template ? '更新模板' : '创建模板')}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
